package com.ygxsk.carhome.ui.care;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventCardDistHistory;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.BaseImmersionFragment;
import com.ygxsk.carhome.ui.adapter.CardDistHistoryAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CardDistHistoryListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CardDistHistoryListFragment extends BaseImmersionFragment {


    @BindView(R.id.refreshlayoutindistfragment)
    SmartRefreshLayout refreshLayoutInDistFragment;

    @BindView(R.id.recyclerviewindistfragment)
    RecyclerView recyclerViewInDistFragment;

    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<>();

    //已核销adapter
    private CardDistHistoryAdapter cardDistHistoryAdapter;

    /**
     * 最后一条上传的id的信息内容
     */
    private int pagination_upLoad = Parameterkey.pageNum_default_first;
    //核销卡券 的弹窗内容，展示卡券的结果；

    //    private CustomDialog customDialog;
    //添加扫码核销的自定义弹窗；
//    private MaterialDialog materialDialogCustomView;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_FLAG_JUMPFROM_WHERE = "flag_jumpfrom_where";
    private static final String ARG_INDEXPOSITION = "indexposition";
    private static final String ARG_INDEXNAME = "indexname";

    // TODO: Rename and change types of parameters
    private int flag_jumpfrom_where;
    private String indexPosition;
    private String indexName;

    public CardDistHistoryListFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static CardDistHistoryListFragment newInstance(int flag_jumpfrom_where, String indexPosition, String indexName) {

        CardDistHistoryListFragment fragment = new CardDistHistoryListFragment();

        Bundle args = new Bundle();

        args.putInt(ARG_FLAG_JUMPFROM_WHERE, flag_jumpfrom_where);

        args.putString(ARG_INDEXPOSITION, indexPosition);
        args.putString(ARG_INDEXNAME, indexName);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (mDataResources == null) {
            mDataResources = new ArrayList<>();
        }

        if (getArguments() != null) {

            flag_jumpfrom_where = getArguments().getInt(ARG_FLAG_JUMPFROM_WHERE);

            indexPosition = getArguments().getString(ARG_INDEXPOSITION);
            indexName = getArguments().getString(ARG_INDEXNAME);

        }

        //核销刷新记录
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initView() {
        super.initView();

        //----------------------------------------------------------------------------------------------------------
        recyclerViewInDistFragment.setLayoutManager(new MyLinearLayoutManager(this.getContext()));

        cardDistHistoryAdapter = new CardDistHistoryAdapter(R.layout.card_dist_history_adapter, mDataResources);
        recyclerViewInDistFragment.setAdapter(cardDistHistoryAdapter);
        cardDistHistoryAdapter.notifyDataSetChanged();

        cardDistHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                // : 2023-07-13 15:07 跳转到这个客户的详情页面??
//                Bundle extra_bundle = new Bundle();
//                extra_bundle.putParcelable(ExtraKey.EXTRA_RUNMANGROUPMANAGEBEAN, runManGroupManageBeanItem);
//                ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);

            }
        });

        cardDistHistoryAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                if (couponCustomerVo != null) {

                    switch (view.getId()) {

                        case R.id.textviewdistcustomerphone: {//拨打

                            //因为要上传编号 业务类型，故要区分开；
                            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                                clickButton_toCallPhone(mActivityInstance, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_8.getIndex());

                            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                                clickButton_toCallPhone(mActivityInstance, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());

                            }

//                            clickButton_toCallPhone(mActivityInstance, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());

                            break;
                        }

                        default:
                            break;
                    }
                }

            }
        });

        refreshLayoutInDistFragment.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {


                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                            getServerDatas_for_rice_tick_history();

                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                            getServerDatas();

                        } else {
                            //额外的
                            getServerDatas();
                        }

//                        getServerDatas();

                        refreshLayout.finishLoadMore();
                    }
                });
            }
        });

//        if (roundButtonAddGroupInRunManGroup != null) {
//            roundButtonAddGroupInRunManGroup.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
//                @Override
//                public void onDebouncingClick(View v) {
//
//                    // : 2023-07-13 15:52 跳转到人员分配列表页面
//                    //跳转到资产的添加页面
//                    Bundle extra_bundle = new Bundle();
////
////                    //String shopId = assetInSideBean.getShopId();
////
////                    //是添加进来的
////                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE,ExtraValue.VALUE_JUMP_FORM_ASSET_ADD);
////
////                    extra_bundle.putString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID,assetInSideBean.getShopId());
////
////                    //携带服务站的列表过去
////                    extra_bundle.putParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET, assetStationInfoListForAddAsset);
////                    //携带资产的归属方
////                    extra_bundle.putParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE, assetUnderBusinessInfoListOutSide);
////                    //
//                    ActivityUtils.startActivity(extra_bundle, LeadManagerGroupActivity.class);
//
//                }
//            });
//        }

    }

    @Override
    protected void initData() {
        super.initData();

        gainDatas();

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        pagination_upLoad = Parameterkey.pageNum_default_first;

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            //判断是从 客户关怀过来还是从-餐券发放过来
            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "getServerDatas_for_rice_tick_history--getServerDatas_for_rice_tick_history");

                getServerDatas_for_rice_tick_history();

            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                getServerDatas();

            } else {
                //额外的
                getServerDatas();
            }

        } else {

            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInDistFragment, false);

        }

    }

    //获取餐券的核销历史页
    private void getServerDatas_for_rice_tick_history() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETGETCUSTOMERCOUPONFORVERIFY_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getGetCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getGetCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        //{"data":"","message":"无数据","code":"20002"}

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            CommUtils.checkCurrently(mFragmentInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                            setEnableLoadmore(refreshLayoutInDistFragment, false);

                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInDistFragment, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        function_apiException(apiException);

                    }
                });

    }


    private void getServerDatas() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COUPONCUSTOMERVOOUTSIDE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //{"data":"","message":"无数据","code":"20002"}
                        //methodNotSuccessData(what_method, serverCode, serverMessage);

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "handlerSomeThingNotSuccessDataForItSelf");

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            CommUtils.checkCurrently(mFragmentInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                            setEnableLoadmore(refreshLayoutInDistFragment, false);

                        } else {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "是空的，页面没有反应");
                        }
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInDistFragment, true);
                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        function_apiException(apiException);

                    }
                });

    }

    private void method_handler_success(CouponCustomerVoOutSide _couponCustomerVoOutSide) {

        if (_couponCustomerVoOutSide != null) {

            ArrayList<CouponCustomerVo> couponCustomerVos = _couponCustomerVoOutSide.getDataList();

            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {
                if (mDataResources != null) {
                    mDataResources.addAll(couponCustomerVos);
                }
            }
        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDataResources != null && mDataResources.isEmpty()) {
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
        }

        pagination_upLoad = _couponCustomerVoOutSide.getNextPagination();

        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
            setFinishLoadMoreWithNoMoreData(refreshLayoutInDistFragment, true);
        } else {
            setEnableLoadmore(refreshLayoutInDistFragment, true);
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_card_dist_history_list;
    }

    @Override
    public void onClickNodata(View view) {

        gainDatas();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCardDist(EventCardDistHistory eventCardDistHistory) {

        if (eventCardDistHistory != null) {

            if (eventCardDistHistory.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_DIST_HISTORY_MAIN_LIST) {

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardDistHistoryAdapter != null) {
                    cardDistHistoryAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }

        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardDistHistoryAdapter != null) {
            cardDistHistoryAdapter.notifyDataSetChanged();
            cardDistHistoryAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

//        CommUtils.checkMaterialDialog(materialDialogCustomView);

        EventBus.getDefault().unregister(this);

    }
}